package student.aistar.Util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionException;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;

/**
 * Mybatis工具类
 */
public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory = null;

    static {
        //类加载的过程 - ClassLoader - loadClass[synchronization修饰的] 线程安全
        //类加载的时候 - 立即执行静态代码块中的代码 - 只会执行一次
        try(InputStream in = Resources.getResourceAsStream("mybatis-config.xml")){
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //获取SqlSession = Connection + Cache
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }

    //关闭SqlSession
    public static void closeSession(SqlSession sqlSession){
        if(sqlSession != null)
            sqlSession.close();
    }

    public static void main(String[] args) {
        SqlSession session = MybatisUtil.getSqlSession();
        System.out.println(session);
    }
}
